package com.system.connect.springboot_flowers.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.system.connect.springboot_flowers.entity.ExperienceLike;
import com.system.connect.springboot_flowers.entity.FlowerExperience;
import com.system.connect.springboot_flowers.service.IExperienceLikeService;
import com.system.connect.springboot_flowers.service.IFlowerExperienceService;
import com.system.connect.springboot_flowers.utils.R;
import com.system.connect.springboot_flowers.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/flower-experience")
public class FlowerExperienceController {

    @Autowired
    private IFlowerExperienceService experienceService;

    @Autowired
    private IExperienceLikeService likeService;

    @PostMapping("/{flowerId}")
    public R<String> createExperience(@PathVariable Long flowerId, @RequestBody FlowerExperience experience) {
        Long userId = Long.valueOf(TokenUtils.getUser());
        experience.setFlowerId(flowerId);
        experience.setUserId(userId);
        experience.setLikes(0);
        experience.setCreateTime(LocalDateTime.now());
        experience.setUpdateTime(LocalDateTime.now());
        experience.setIsDeleted(false);
        
        experienceService.save(experience);
        return R.success(experience.getId().toString());
    }

    @GetMapping("/{flowerId}")
    public R<List<FlowerExperience>> getExperienceList(@PathVariable Long flowerId) {
        QueryWrapper<FlowerExperience> wrapper = new QueryWrapper<>();
        wrapper.eq("flower_id", flowerId)
              .eq("is_deleted", false)
              .orderByDesc("create_time");
        List<FlowerExperience> experiences = experienceService.list(wrapper);
        return R.success(experiences);
    }

    @PostMapping("/like/{experienceId}")
    public R<Void> likeExperience(@PathVariable Long experienceId) {
        Long userId = Long.valueOf(TokenUtils.getUser());
        
        // 检查是否已经点赞
        QueryWrapper<ExperienceLike> wrapper = new QueryWrapper<>();
        wrapper.eq("experience_id", experienceId)
              .eq("user_id", userId);
        if (likeService.count(wrapper) > 0) {
            return R.error("已经点赞过了");
        }

        // 添加点赞记录
        ExperienceLike like = new ExperienceLike();
        like.setExperienceId(experienceId);
        like.setUserId(userId);
        like.setCreateTime(LocalDateTime.now());
        likeService.save(like);

        // 更新经验点赞数
        FlowerExperience experience = experienceService.getById(experienceId);
        if (experience != null) {
            experience.setLikes(experience.getLikes() + 1);
            experienceService.updateById(experience);
        }

        return R.success(null);
    }
} 